package com.asset.service.impl;

import com.asset.web.interceptor.LoginInterceptor;
import com.asset.mapper.PurchaseDetailMapper;
import com.asset.mapper.PurchaseMapper;
import com.asset.pojo.Purchase;
import com.asset.pojo.PurchaseDetail;
import com.asset.pojo.User;
import com.asset.service.PurchaseService;
import com.asset.util.AssetExceptionEnum;
import com.asset.util.AssetManageException;
import com.asset.util.BaseApprovalStatus;
import com.asset.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 采购管理
 * @author 11725
 */
@Slf4j
@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Resource
    private PurchaseMapper purchaseMapper;

    @Resource
    private PurchaseDetailMapper detailMapper;

    @Override
    public PageResult<Purchase> selectByPage(Integer page, Integer rows, Long depaId, Integer status) {
        PageHelper.startPage(page, rows);

        Example example = new Example(Purchase.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("depaId", depaId);
        if (status != null) {
            criteria.andEqualTo("status", status);
        }
        example.orderBy("applyTime").desc();

        List<Purchase> list = purchaseMapper.selectByExample(example);
        PageInfo<Purchase> info = new PageInfo<>(list);

        return new PageResult<>(info.getTotal(), list);
    }

    @Override
    public PurchaseDetail selectById(Long id) {
        return detailMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(BigDecimal applyFund, PurchaseDetail detail) {
        User user = LoginInterceptor.getUser();
        // 1. 新增采购记录
        Purchase record = new Purchase();
        record.setUserId(user.getId());
        record.setDepaId(user.getDepaId());
        record.setStatus(BaseApprovalStatus.WAIT_APPROVAL);
        record.setApplyFund(applyFund);
        // 默认审批金额与申请金额一致
        record.setApprovalFund(applyFund);
        record.setApplyTime(new Date());

        purchaseMapper.insertSelective(record);

        // 2. 新增采购清单
        detail.setId(record.getId());
        detailMapper.insertSelective(detail);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDetail(PurchaseDetail detail) {
        int row = detailMapper.update(detail.getId(), detail.getList());
        if (row != 1) {
            throw new AssetManageException(AssetExceptionEnum.PURCHASE_DETAIL_UPDATE_FAIL);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Long id) {
        // 删除采购单记录
        int row = purchaseMapper.deleteByPrimaryKey(id);

        // 删除关联的采购清单
        if (row == 1) {
            detailMapper.deleteByPrimaryKey(id);
        } else {
            throw new AssetManageException(AssetExceptionEnum.PURCHASE_INFO_NOT_FOUND);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Purchase purchase) {
        // 查询数据
        Purchase result = purchaseMapper.selectByPrimaryKey(purchase.getId());

        if (result == null) {
            // 不存在
            throw new AssetManageException(AssetExceptionEnum.PURCHASE_INFO_NOT_FOUND);
        }
        log.info("[service:purchase:update-status] id: {}, now-status: {}", result.getId(), result.getStatus());

        if (!result.getStatus().equals(BaseApprovalStatus.WAIT_APPROVAL)) {
            // 错误的审批状态
            throw new AssetManageException(AssetExceptionEnum.PURCHASE_INFO_STATUS_ERROR);
        }

        Purchase record = new Purchase();
        record.setId(purchase.getId());
        if (Objects.equals(BaseApprovalStatus.ALLOW_PURCHASE, purchase.getStatus())) {
            // 已批准，记录审批金额
            record.setApprovalFund(purchase.getApprovalFund());
        } else if (!Objects.equals(BaseApprovalStatus.NOT_PASS_APPROVAL, purchase.getStatus())) {
            // 错误的审批状态
            throw new AssetManageException(AssetExceptionEnum.PURCHASE_INFO_STATUS_ERROR);
        }
        // 记录新状态
        record.setStatus(purchase.getStatus());
        // 记录审批时间
        record.setApprovalTime(new Date());

        // 更新
        log.info("[service:purchase:update-status] id: {}, new-status: {}", record.getId(), record.getStatus());
        purchaseMapper.updateByPrimaryKeySelective(record);
    }
}
